package org.geeks.gsspringsecurity.base.config;

import java.util.ArrayList;
import java.util.List;

import org.geeks.gsspringsecurity.biz.domain.User;
import org.geeks.gsspringsecurity.biz.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * Security config
 * 
 * @author Geek-S
 *
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private UserRepository userRepository;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
	}

	@Bean
	public UserDetailsService userDetailsService() {
		return new UserDetailsService() {

			@Override
			public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

				User user = userRepository.findByUsername(username);

				if (user == null) {
					throw new UsernameNotFoundException("UsernameNotFound");
				} else {
					List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

					user.getRoles().forEach(role -> {
						role.getAuthorities().forEach(authority -> {
							grantedAuthorities.add(new SimpleGrantedAuthority(authority.getTag()));
						});
					});

					return new org.springframework.security.core.userdetails.User(user.getUsername(),
							user.getPassword(), grantedAuthorities);
				}
			}
		};
	}

}